<?php
namespace app\h5\Controller;
use Think\Controller;
use Think\Exception;

use app\admin\model\BookModel;
use app\admin\model\WordModel;
use app\admin\model\MemberModel;
use app\admin\model\StudyModel;
class Wechat extends \think\Controller{
    private static $appid = WX_APPID;
    private static $secret = WX_SECRET;  
    /**
     * 首页
     */
    public function login_wechat(){
        $memberModel = new MemberModel;
        $openid = session('openid');
        if(!$openid){
            $uri= APP_REQUEST;
            $result = $this->to_wx($uri);
        }
        $member = $memberModel->getOnemember(['openid' => $openid]);
        if(empty($member)){
            $header_img_url = get_web_pic(session('user_info.headimgurl'));
            $insert_data = [
                'person_name' => session('user_info.nickname'),
                'person_img' => $header_img_url,
                'openid' => session('user_info.openid'),
                'addtime' => NOW_TIME
            ];
            $memberModel->addmember($insert_data);    
        }
        return $member;
    }
    /*今日学习*/
    public function index(){
        $member = $this->login_wechat();
        $day_num = (int)((time() - strtotime($member['addtime'])) / 86400);
        /*今日绘本*/
        $book = new bookModel();
        $word = new wordModel();
        $book_data = $book->getOnebook(['recommend_date' => date('Y-m-d')],'*');
        $word_num = $word->getAllwords(['recommend_date' => date('Y-m-d'),'is_put' => '1']);
        $this->assign([
            'member' => $member,
            'day_num' => $day_num,
            'book_data' => $book_data,
            'word_num' => $word_num
        ]);
        return $this->fetch();
    }
    /*学习记录*/
    public function study_recorde(){
        $member = $this->login_wechat();

        return $this->fetch();
    }
    public function computer(){
        $member = $this->login_wechat();
        $word = new wordModel();
        $list = $word->getwords(['recommend_date' => date('Y-m-d'),'is_put' => '1']);
        if(empty($list)){
            $this->redirect('wechat/index', 5, '页面跳转中...');
        }
        
        return $this->fetch();
    }
    /*家长日历*/
    public function parent_today(){
        $member = $this->login_wechat();
        return $this->fetch();
    }
    /*我的*/
    public function my(){
        $member = $this->login_wechat();
        $study = new studyModel();
        $word_num = $study->getAllstudys(['user_id' => $member['id']]);
        $member['word_num'] = $word_num; 
        $this->assign(['member' => $member]);
        return $this->fetch();
    }
    /*学单词翻译*/
    public function study_word(){
        $member = $this->login_wechat();
        $word = new wordModel();
        $study = new studyModel();
        $list = $word->getwords(['recommend_date' => date('Y-m-d'),'is_put' => '1']);
        if(empty($list)){
            $this->redirect('wechat/index', 5, '页面跳转中...');
        }
        foreach($list as $key=>$vo){
            $list[$key]['pic'] = json_decode($vo['pic']);
            $list[$key]['translate'] = json_decode($vo['translate']);
            $list[$key]['correct'] = json_decode($vo['translate']['0']);
        }
        $word_num = count($list);
        $num = input('num');
        if($num){
            $list[$num]['correct'] = $list[$num]['translate'][0];
            $translate = $list[$num]['translate'];
            shuffle($translate);
            $list[$num]['translate'] = $translate;
            if($num < $word_num-1){
                $list[$num]['num'] = $num+1;
            }else{
                $list[$num]['num'] = $num;
            }
            $list[$num]['percent'] = ((($num+1)/$word_num)*100).'%';
            $study_word = $study->getOnestudy(['word_id' => $list[$num]['id'],'user_id' => $member['id']]);
            if(empty($study_word)){
                $study->addstudy(
                    ['word_id' => $list[$num]['id'],
                     'user_id' => $member['id'],
                     'recommend_date' => $list[$num]['recommend_date'],
                     'addtime' => date('Y-m-d h:i:s',time())
                 ]);
            }
            $this->assign(['data' => $list[$num]]);
        }else{
            $list[0]['correct'] = $list[0]['translate'][0];
            $translate = $list[0]['translate'];
            shuffle($translate);
            $list[0]['translate'] = $translate;
            $list[0]['num'] = 1;
            $list[0]['percent'] = ((1/$word_num)*100).'%';
            $study_word = $study->getOnestudy(['word_id' => $list[0]['id'],'user_id' => $member['id']]);
            if(empty($study_word)){
                $study->addstudy(
                    ['word_id' => $list[0]['id'],
                     'user_id' => $member['id'],
                     'recommend_date' => $list[0]['recommend_date'],
                     'addtime' => date('Y-m-d h:i:s',time())
                 ]);
            }
            $this->assign(['data' => $list[0]]);
        }
        return $this->fetch();
    }
    /*绘本内容*/
    public function book_content(){
        $member = $this->login_wechat();
        $book = new bookModel();
        if(request()->isAjax()){
           $post = input('post.');
           $book_content = $book->get_all_books('title,correct,pic,audio',['pid' => $post['book_id']]);
           $book_num = count($book_content);
           if(($post['page'] <= $book_num-1) && $post['page'] >= -1){
                if($post['page'] == '-1'){
                    $return_data = $list = $book->getOnebook(['recommend_date' => date('Y-m-d'),'is_put' => '1'],'title,correct,pic,audio');
                    $return_data['book_num'] = $book_num;
                    $return_data['percent'] = 0;  
                }else{
                    $return_data = $book_content[$post['page']];
                    $return_data['percent'] = ((($post['page']+1)/$book_num)*100).'%'; 
                }
              /*标题处理*/
                $word = new wordModel();
                $word_list = $word->getwords(['recommend_date' => date('Y-m-d'),'is_put' => '1'],'title,audio');
                foreach($word_list as $key => $val){
                    $return_data['title'] = str_ireplace($val['title'],"<span class='title_color' onclick='play(".$key.")'>".$val['title']."</span> <audio hidden class='play".$key."' src='".$val['audio']."' controls='controls'> </audio>", $return_data['title']);
                }
                $return_data['code'] = '200';
           }else{
                $return_data['code'] = '500';
           }
           return json($return_data);
        }else{
            $list = $book->getOnebook(['recommend_date' => date('Y-m-d'),'is_put' => '1'],'*');
            if(empty($list)){
                $this->redirect('wechat/index', 5, '页面跳转中...');
            }
            $this->assign(
                [
                    'books' => $list,
                ]
            );
            return $this->fetch();
            
        }
    }
    /*听绘本*/
    public function book(){
        $member = $this->login_wechat();     
        $param = input('param.');
        $limit = 9;
        $where = ['is_del' => '0','is_put' => '1','pid' => '0'];
        if(!isset($param['pageNumber'])){
            $param['pageNumber'] = '1';
        }
        $offset = ($param['pageNumber'] - 1) * $limit;
        $book = new bookModel();
        $selectResult = $book->getbooksByWhere($where, $offset, $limit);
        for($i = 0;$i<count($selectResult);$i++){
            $selectResult[$i]['addtime'] = substr($selectResult[$i]['addtime'],0,-9);
        }
        if($param['pageNumber'] > 1){
            return json($selectResult);
        }else{
            $this->assign(
                ['book' => $selectResult]
                    ); 
            return $this->fetch();
        }
    }
    /*邀请好友*/
    public function invite_friends(){
        return $this->fetch();
    }
    /*训练营*/
    public function train(){
        return $this->fetch();
    }
    /*购买书籍*/
    public function buy_book(){
        return $this->fetch();
    }
    public function to_wx($uri){
        $redirect_uri='http://'.APP_HTTP_HOST.'/h5/wechat/notity?u='.urlencode($uri);
        $data=[
            'appid'=>self::$appid,
            'redirect_uri'=>$redirect_uri,
            'response_type'=>'code',
            'scope'=>'snsapi_userinfo',//snsapi_base,//snsapi_userinfo
            'state'=>'1'
        ];
        $parameter = http_build_query($data);
        $url='https://open.weixin.qq.com/connect/oauth2/authorize?'.$parameter;
        $this->redirect($url);//重定向到微信服务器，微信服务器重定向到weixin/users/notity
    }
    /*微信服务器回调*/
    public function notity(){
        $return_data=empty($_GET)?'':$_GET;
        if($return_data===''){exit('无效请求');}
        if($return_data['state']=='1'){
            $code=$return_data['code'];
        }else{
            exit('异常请求');
        }
    
        //获取access_token
        $url='https://api.weixin.qq.com/sns/oauth2/access_token?';
        $data=array(
            'appid'=>self::$appid,
            'secret'=>self::$secret,
            'code'=>$code,
            'grant_type'=>'authorization_code',//snsapi_base,//snsapi_userinfo
        );
        $parameter = http_build_query($data);
        $json_data = _curl($url.$parameter,'GET');
        //获取用户信息
        $user_info = $this->get_wechatdata($json_data);
        session('user_info',$user_info);
        session('openid',$json_data['openid']);
        $url=urldecode($_GET['u']);
        $redirect_uri='http://'.$_SERVER['HTTP_HOST'].$url;
        $this->redirect($redirect_uri);
    }
    /*
    * 获取 微信用户信息
    */
    public function get_wechatdata($token_data){
        $data = array(
            'access_token' => $token_data['access_token'],
            'openid' => $token_data['openid'],
            'lang' => 'zh_CN'
            );
        $data_url = 'https://api.weixin.qq.com/sns/userinfo?';
        $parameter = http_build_query($data);
        $wechat_data = _curl($data_url.$parameter,'GET');
        return $wechat_data;
    }
    

}

